import { CouponOperate, ShoppingWay } from "../../core/enum"
import { Cart } from "../../models/cart"
import { Coupon } from "../../models/coupon"
import { CouponBO } from "../../models/coupon-bo"
import { Order } from "../../models/order"
import { OrderItem } from "../../models/order-item"
import { OrderPost } from "../../models/order-post"
import { Payment } from "../../models/payment"
import { Sku } from "../../models/sku"

// pages/order/order.js
const cart = new Cart()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        currentCouponId: null,
        order: null,
        totalPrice: 0,
        finalTotalPrice: 0,
        discountMoney: 0,
        address: null,
        submitBtnDisable: false,
        orderFail: false,
        orderFailMsg: '',
        isOk: true,
        shoppingWay: ShoppingWay.BUY
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function (options) {
        let orderItems
        let localItemCount

        const shoppingWay = options.way
        this.data.shoppingWay = shoppingWay

        if (shoppingWay === ShoppingWay.BUY) {
            const skuId = options.sku_id
            const count = options.count
            orderItems = await this.getSingleOrderItems(skuId, count)
            localItemCount = 1
        } else {
            const skuIds = cart.getCheckedSkuIds()
            orderItems = await this.getCartOrderItems(skuIds)
            localItemCount = skuIds.length
        }

        const order = new Order(orderItems, localItemCount)
        this.data.order = order
        try {
            order.checkOrderIsOk()
        } catch (error) {
            console.error(error)
            this.setData({
                isOk: false
            })
        }

        const myCoupons = await Coupon.getMySelfWithCategory()
        const couponBOList = this.pakeageCouponBoList(myCoupons, order)
        const totalPrice = order.getTotalPrice()
        this.setData({
            orderItems,
            totalPrice,
            couponBOList: couponBOList,
            finalTotalPrice: order.getTotalPrice()
        })
    },
    async getSingleOrderItems(skuId, count) {
        const skus = await Sku.getSkuIds(skuId)
        return [new OrderItem(skus[0], count)]
    },
    // 同步更新sku数据 
    async getCartOrderItems(skuIds) {
        const skuList = await Sku.getSkuIds(skuIds)
        const orderItems = this.packageOrderItems(skuList)
        return orderItems

    },
    onChooseCoupon(event) {
        const couponObj = event.detail.coupon
        const couponOperate = event.detail.operate
        if (couponOperate === CouponOperate.PICK) {
            this.data.currentCouponId = couponObj.id
            const priceObj = CouponBO.getFinalTotalPrice(this.data.order.getTotalPrice(), couponObj)

            this.setData({
                finalTotalPrice: priceObj.finalPrice,
                discountMoney: priceObj.discountMoney
            })
        } else {
            this.data.currentCouponId = null
            this.setData({
                finalTotalPrice: this.data.order.getTotalPrice(),
                discountMoney: 0
            })
        }
    },

    pakeageCouponBoList(coupons, order) {
        return coupons.map(coupon => {
            const couponBO = new CouponBO(coupon)
            couponBO.meetCondition(order)
            return couponBO
        });
    },

    packageOrderItems(skus) {
        return skus.map((sku) => {
            const count = cart.getSkuCountBySkuId(sku.id)
            return new OrderItem(sku, count)
        })
    },

    async onSubmit(event) {
        if (!this.data.address) {
            wx.showToast({
                title: '请选择收获地址',
                icon: 'none',
                duration: 3000,
            });
            return
        }

        this.disableSubmitBtn()

        const orderPost = new OrderPost(
            this.data.totalPrice,
            this.data.finalTotalPrice,
            this.data.currentCouponId,
            this.data.order.getOrderSkuInfoList(),
            this.data.address
        )
        console.log(orderPost);
        const oid = await this.postOrder(orderPost)
        if (!oid) {
            this.enableSubmitBtn()
            return
        }
        if (this.data.shoppingWay === ShoppingWay.CART) {
            cart.removeCheckedItems()
        }
        // 支付小程序/前端支付
        // 支付参数调用API
        // 支付wx.requestPayment(params)
        // API => params


        wx.lin.showLoading({
            type: "flash",
            fullScreen: true,
            color: "#157658"

        });

        const payParams = await Payment.getPayParams(oid)
        if (!payParams) {
            return
        }
        try {
            const res = await wx.requestPayment(payParams);
            wx.redirectTo({
                url: `/pages/pay-success/pay-success?oid=${oid}`,
            });
            console.log("success:", res);
        } catch (error) {
            wx.redirectTo({
                url: `/pages/my-order/my-order?key=${1}`,
            });
            console.log("error:", error);
        }
    },

    async postOrder(orderPost) {
        try {
            const serverOrder = await Order.postOrderToServer(orderPost)
            if (serverOrder) {
                return serverOrder.id
            }
        } catch (e) {
            this.setData({
                orderFail: true,
                orderFailMsg: e.message
            })
        }
    },

    disableSubmitBtn() {
        this.setData({
            submitBtnDisable: true
        })
    },
    enableSubmitBtn() {
        this.setData({
            submitBtnDisable: false
        })
    },
    onChooseAddress(event) {
        const address = event.detail.address

        this.data.address = address
    }


})